import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router'

export const useUserStore = defineStore(
  'DisasterUser',
  () => {
    // 用户角色：admin-管理员，guest-普通用户，null-未登录
    const role = ref<string | null>(null)
    const username = ref<string>('')

    // 硬编码的用户账号
    const users = [
      { username: 'admin', password: 'admin123', role: 'admin' },
      { username: 'guest', password: 'guest123', role: 'guest' }
    ]

    // 登录方法
    const login = (loginUsername: string, loginPassword: string): boolean => {
      const user = users.find(
        (u) => u.username === loginUsername && u.password === loginPassword
      )

      if (user) {
        role.value = user.role
        username.value = user.username
        return true
      }
      return false
    }

    // 登出方法
    const logout = () => {
      role.value = null
      username.value = ''
      router.push('/login')
    }

    // 检查是否已登录
    const isLoggedIn = (): boolean => {
      return role.value !== null
    }

    return {
      role,
      username,
      login,
      logout,
      isLoggedIn
    }
  },
  {
    persist: true // 启用状态持久化
  }
)
